//
//  RCCityListVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-5-29.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCCityListVC.h"
#import "GloableEngineService.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "RCSearchAllCityTagDataModel.h"
#import "RCSearchCityListDataModel.h"
#import "NSArray+EX.h"
#import "NSString+NSString_Ex_.h"
#import "AppDelegate.h"


#define kSearchImageFile          @"image_search_searchBar.png"
#define kSearchIconImageFile      @"image_tabbar_search_normal.png"

#define kTextPlaceHolder          @"输入城市名或首字母查询"

#define kHeaderImageFile        @"image_cityList_header_BG.png"
#define kContentImageFile       @"image_cityList_content_BG.png"

@interface RCCityListVC ()<IManagerDelegate,UITextFieldDelegate>{
    UITextField    *_searchTextField;
    BOOL           searchMode;
    
    NSMutableArray *_filterCityArray;

}

@property(nonatomic,retain) MBProgressHUDEx *progressHub;
@property(nonatomic,assign) int64_t requestID;
@property(nonatomic,retain) RCSearchCityListDataModel *dataModel;
@property(nonatomic,retain) NSMutableDictionary *keyValues;

@property(nonatomic,retain) NSMutableArray *fileterCityArray;
@property(nonatomic,assign) BOOL isRefreshLocation;
@end

@implementation RCCityListVC

@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;
@synthesize dataModel = _dataModel;
@synthesize keyValues = _keyValues;

@synthesize fileterCityArray = _filterCityArray;
@synthesize isRefreshLocation = _isRefreshLocation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        // Custom initialization
        [[NSNotificationCenter defaultCenter]  addObserver:self
                                                  selector:@selector(cityNameChanged:) name:@"CityNameChanged"
                                                    object:nil];
    }
    return self;
}


- (void) dealloc
{
    [[NSNotificationCenter defaultCenter]  removeObserver:self
                                                     name:@"CityNameChanged"
                                                   object:nil];
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.dataModel = nil;
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self createSearchView];

	// Do any additional setup after loading the view.
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y+40,baseVCTableView.frame.size.width,baseVCTableView.frame.size.height-self.navigationController.navigationBar.frame.size.height-4-40);
        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
        [self addPullRefresh];
//        baseVCTableView.sectionIndexColor = kNormalHeadTextColor;
//        baseVCTableView.sectionIndexBackgroundColor = kNormalTextColor;
//        baseVCTableView.sectionIndexTrackingBackgroundColor = kNormalOrangeTextColor;
        
    }
    [self refreshData];
    [self requestData];

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
}

-(void)requestData{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [_progressHub show:YES];
    [self.view bringSubviewToFront:_progressHub];
    _requestID = [[IManager sharedInstance]requestCityList:self];
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        self.dataModel = (RCSearchCityListDataModel *)dataModel;
        
        for (RCSearchCityListItem *item in self.dataModel.cityListArray) {
            NSString *firstLetters = [[item.cityLetters substringToIndex:1] uppercaseString];
            if (self.keyValues == nil) {
                self.keyValues = [[[NSMutableDictionary alloc] init] autorelease];
            }
            NSMutableArray *arr = [self.keyValues objectForKey:firstLetters];
            if (arr == nil || [arr count] == 0) {
                arr = [[NSMutableArray alloc] init];
                [arr addObject:item];
                [self.keyValues setValue:arr forKey:firstLetters];
                [arr release];
            }
        }
        
        [baseVCTableView reloadData];
    }
}

- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma 
#pragma mark tableview delegate and datasource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    if (searchMode) {
        return 1;
    }else{
        return 1+ [[self.keyValues allKeys] count];
    }
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (searchMode) {
            return [self.fileterCityArray count];
        }
        return 1;
    }else{
        
//        NSString *key =  [[self.keyValues allKeys] objectAtIndex:(section-1)];
        NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
            RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
            RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
            return [obj1.cityLetters compare:obj2.cityLetters];
        }];
        NSString *key = [orderedKeys objectAtIndex:(section -1)];
        NSMutableArray *arr = [self.keyValues objectForKey:key];
        return [arr count];
        
        
        if (self.dataModel == nil || self.dataModel.cityListArray == nil || [self.dataModel.cityListArray count]==0) {
            return 0;
        }else{
            return [self.dataModel.cityListArray count];
        }
        
    }
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (searchMode) {
        return nil;
    }
    NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
        RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
        RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
        return [obj1.cityLetters compare:obj2.cityLetters];
    }];
    
    return orderedKeys;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    
//    NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
//        RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
//        RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
//        return [obj1.cityLetters compare:obj2.cityLetters];
//    }];
    return index +1;
    
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    
//    if([arrayOfCharacters count]==0)
//        
//        ｛
//        
//        return @”";
//        
//        ｝
//        
//        return [arrayOfCharacters objectAtIndex:section];
//    
//}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[[UITableViewCell alloc] init] autorelease];
    NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kContentImageFile];
    UIImage *bgImage = [UIImage imageWithContentsOfFile:filePath];
    cell.contentView.layer.contents = (id)bgImage.CGImage;
//    cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:filePath]];
    
    cell.textLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    cell.textLabel.textColor = [UIColor colorWithHex:0xff505050];
    cell.textLabel.frame = CGRectMake(14, 20, 200, 16);
    if ([indexPath section] == 0) {
        if (searchMode) {
            NSInteger row = [indexPath row];
            NSString *cityName = @"";
            if (self.fileterCityArray) {
                RCSearchCityListItem *item = [self.fileterCityArray safeObjectAtIndex:row];
                if (item && ![NSString stringIsNullOrEmpty:item.cityName]) {
                    cityName = item.cityName;
                }
            }
            cell.textLabel.text = cityName;
        }else{
            if ([baseVCTableView pullTableIsRefreshing] || self.isRefreshLocation) {
                cell.textLabel.text = @"更新中...";
            }else{
                cell.textLabel.text = [[GloableEngineService sharedInstance] userCityName];
            }
        }
        
    }else{
        NSInteger row = [indexPath row];
        NSString *cityName = @"";
        
        NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
            RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
            RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
            return [obj1.cityLetters compare:obj2.cityLetters];
        }];
        NSString *key = [orderedKeys objectAtIndex:([indexPath section] -1)];
        NSMutableArray *arr = [self.keyValues objectForKey:key];

        
        
//        if (self.dataModel && self.dataModel.cityListArray) {
            RCSearchCityListItem *item = [arr safeObjectAtIndex:row];
            if (item && ![NSString stringIsNullOrEmpty:item.cityName]) {
                cityName = item.cityName;
            }
//        }
        cell.textLabel.text = cityName;
    }
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)]autorelease];
    NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kHeaderImageFile];
    UIImage *bgImage = [UIImage imageWithContentsOfFile:filePath];
    headView.layer.contents = (id)bgImage.CGImage;
//    headView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:filePath]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(14, 9, 150, 12)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    
    if (section == 0) {
        label.text = @"GPS定位城市";
    }else{
        NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
            RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
            RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
            return [obj1.cityLetters compare:obj2.cityLetters];
        }];
        NSString *key = [orderedKeys objectAtIndex:(section -1)];
        label.text = key;
    }
    [headView addSubview:label];
    [label release];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (searchMode) {
        return 0;
    }else{
        return 30;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
    if (searchMode) {
        RCSearchCityListItem *item = [self.fileterCityArray safeObjectAtIndex:[indexPath row]];
        [GloableEngineService sharedInstance].selectedCityName = item.cityName;
        [GloableEngineService sharedInstance].selectedCityID = item.cityID;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"SelectCityChanged" object:nil];
        
        [self performSelector:@selector(popViewController) withObject:nil afterDelay:1.0];
        return;

    }
    
    
    if ([indexPath section] ==0) {
        if ([[GloableEngineService sharedInstance] userCityName] != nil){
            [GloableEngineService sharedInstance].selectedCityName = [[GloableEngineService sharedInstance] userCityName];
            [GloableEngineService sharedInstance].selectedCityID = nil;
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"SelectCityChanged" object:nil];
            
            [self performSelector:@selector(popViewController) withObject:nil afterDelay:1.0];
            return;
        }

    }else{
        
        if (self.dataModel && self.dataModel.cityListArray) {
//<<<<<<< .mine
            NSArray *orderedKeys = [self.keyValues keysSortedByValueUsingComparator:^NSComparisonResult(NSMutableArray *arr1, NSMutableArray *arr2){
                RCSearchCityListItem *obj1 = [arr1 objectAtIndex:0];
                RCSearchCityListItem *obj2 = [arr2 objectAtIndex:0];
                return [obj1.cityLetters compare:obj2.cityLetters];
            }];
            NSString *key = [orderedKeys objectAtIndex:([indexPath section] -1)];
            NSMutableArray *arr = [self.keyValues objectForKey:key];
            
            RCSearchCityListItem *item = [arr safeObjectAtIndex:[indexPath row]];
//=======
//            
//            NSArray *keyArray = [self.keyValues allKeys];
//            NSString *key = [keyArray safeObjectAtIndex:[indexPath section]-1];
//            if ([NSString stringIsNullOrEmpty:key]) {
//                [RCAppDelegate alertWithCustomizeString:@"数据错误"];
//                return;
//            }
//            NSArray *valueArray = [self.keyValues valueForKey:key];
//            if (nil == valueArray && [valueArray count] == 0) {
//                [RCAppDelegate alertWithCustomizeString:@"数据错误"];
//                return;
//            }
//            
//            RCSearchCityListItem *item = [valueArray safeObjectAtIndex:[indexPath row]];
//            
//>>>>>>> .r301
            if (item != nil) {
                if (![NSString stringIsNullOrEmpty:item.cityName] && ![NSString stringIsNullOrEmpty:item.cityID]) {
                    [GloableEngineService sharedInstance].selectedCityName = item.cityName;
                    [GloableEngineService sharedInstance].selectedCityID = item.cityID;
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"SelectCityChanged" object:nil];
                    
                    [self performSelector:@selector(popViewController) withObject:nil afterDelay:1.0];
                    return;
                }
                
            }
        }
        
    }
    
    [RCAppDelegate alertWithCustomizeString:@"数据错误"];
    
}

-(void)popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) refreshData
{
    self.isRefreshLocation = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CS_LocationFinished_Msg object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(locationFinished:)
                                                 name:CS_LocationFinished_Msg                                                   object:nil];
    [[GloableEngineService sharedInstance] updataUserLocation];

}

- (void)locationFinished:(NSNotification *)notif
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CS_LocationFinished_Msg object:nil];
    
    self.isRefreshLocation = NO;
    if (1 == [(NSString*)[notif object] intValue])
    {
        [baseVCTableView reloadData];
    }
    else
    {
        if ([GloableEngineService sharedInstance].locationInfo)
        {//使用上一次
            [baseVCTableView reloadData];
        }
        
        
    }
}


-(void) cityNameChanged:(NSNotification *)notification
{
    NSDictionary *dic = (NSDictionary *)[notification object];
    NSLog(@"dic cityname :%@",[dic objectForKey:@"CityName"]);
    [self finishRefreshingData];
    
}


- (void) createSearchView
{
    UIImageView *searchImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 3, 310, 34)];
    searchImageView.userInteractionEnabled = YES;
    searchImageView.backgroundColor = [UIColor clearColor];
    NSString *searchpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kSearchImageFile];
    [searchImageView setImage:[UIImage imageWithContentsOfFile:searchpath]];
    
    UIImageView *searchIconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 15, 16)];
    searchIconImageView.backgroundColor = [UIColor clearColor];
    NSString *searchIconpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kSearchIconImageFile];
    [searchIconImageView setImage:[UIImage imageWithContentsOfFile:searchIconpath]];
    [searchImageView addSubview:searchIconImageView];
    [searchIconImageView release];
    
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 5, 280, 24)];
        _searchTextField.borderStyle = UITextBorderStyleNone;
        _searchTextField.delegate = self;
        _searchTextField.placeholder = kTextPlaceHolder;
        _searchTextField.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
        _searchTextField.textAlignment = UITextAlignmentLeft;
        _searchTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        _searchTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textFieldDidChange:)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:nil];
    }
    
    [searchImageView addSubview:_searchTextField];
    [searchImageView bringSubviewToFront:_searchTextField];
    
    [self.viewContainer addSubview:searchImageView];
    [searchImageView release];
}


- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
    searchMode = YES;
    return YES;
}



- (void)textFieldDidChange :(NSNotification *)notif
{
    //
    NSString *inputStr = [_searchTextField text];
    
    if ([NSString stringIsNullOrEmpty:inputStr]) {
        searchMode = NO;
        }else{
            searchMode = YES;
        [self.fileterCityArray removeAllObjects];
        for (RCSearchCityListItem *item in self.dataModel.cityListArray) {
            NSRange range = [item.cityLetters rangeOfString:inputStr];
            if (range.location != NSNotFound && range.length != 0) {
                [self.fileterCityArray addObject:item];
            }
        }
    }
   
    [baseVCTableView reloadData];
    
}

- (NSMutableArray *) fileterCityArray
{
    if (_filterCityArray == nil) {
        _filterCityArray = [[NSMutableArray alloc] init];
    }
    return _filterCityArray;
}
@end
